package com.hfjc.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hfjc.entity.Product;
import com.hfjc.entity.ResultBack;
import com.hfjc.service.impl.ProductService;
import com.hfjc.util.ResultBackUtil;

@RestController
@RequestMapping("/product")
public class ProductController {
	
	@Autowired
	private ProductService productService;
	
	@RequestMapping(value="/product",method=RequestMethod.GET)
	public String product(){
		return "product";
	}
	
	/**
	 * 获得产品列表
	 * @return
	 */
	@GetMapping(value="/list")
	public List<Product> productsList(){
		return productService.findAll();
	}
	/**
	 * 增加产品
	 * @param products
	 * @return
	 */
	@PostMapping(value="/add")
	public ResultBack<Product> productAdd(@Valid Product product,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return ResultBackUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		
		return ResultBackUtil.success(productService.productAdd(product));
	}
	/**
	 * 根据ID获得单个产品
	 * @param id
	 * @return
	 */
	@GetMapping(value="/find/{id}")
	public Product findProductsById(@PathVariable("id") Integer id) {
		return productService.findProductsById(id);
	}
	/**
	 * 根据ID更新相关的产品
	 * @param id
	 * @param productName
	 * @param price
	 * @return
	 */
	@PostMapping(value="/update/{id}")
	public Product updateProductsById(@PathVariable("id") Integer id,@RequestParam("productName") String productName,@RequestParam("price") Float price) {
		return productService.updateProductsById(id,productName,price);
	}
	/**
	 * 根据ID删除产品
	 * @param id
	 */
	@PostMapping(value="/del/{id}")
	public String delProductsById(@PathVariable("id") Integer id) {
		return productService.delProductsById(id);
	}
	
	@PostMapping(value="/list/price/{price}")
	public List<Product> findProductsByPrice(@PathVariable("price")Float price) {
		return productService.findProductsByPrice(price);
	}
	
	@GetMapping(value="/getPrice/{id}")
	public void getPriceById(@PathVariable("id") Integer id) throws Exception{
		productService.findPriceById(id);
	}
	
}
